/* Copyright Andy Mitchell 2007. No warranties */

function GTDInboxPage(gtdinboxBrowser, doc){
	this.id = (new Date()).valueOf();
	this.gtdinboxBrowser = gtdinboxBrowser;
	this.db = gtdinboxBrowser.db;
	this.sp = new StoredProcedures(this);
	this.settings = gtdinboxBrowser.settings;
	this.eventObservers = new EventObservers(this);
		
	this.doc = doc;
	this.window = doc.defaultView;
	this.unsafeWindow = this.window.wrappedJSObject;
	this.attachToBrowser();
	
	
	var gtdFrame = this.doc.location.href.match(/gtd\=(\d+)/i);
	if( gtdFrame ) gtdFrame = gtdFrame[1];	// a unique id	
	

	this.unsafeWindow.GTDCallBack = GIPROTOTYPE.bind(this, function(g){
		
		if( !this._firstGMonkey ){
		
			if( !this.unsafeWindow.console ){
				this.unsafeWindow.console = {log: function(){}, trace: function(){}};
			}
			
			if( !g || !g.getActiveViewElement ){
				if( GTDDEBUGMODE ) alert("gtdinboxPage GTDCallBack - could not find gmail");
				return;	// error
			}
			
			
			this.gmailDOM = new GmailDOM(this);
			this.gmailDOM.viewChange(g);
			
			this._firstGMonkey = true;
			try{
				this._gmail = g;
				if( gtdFrame ){	// Strip it
					
					var el = g.getMastheadElement();
					el.style.display = "none";
					var el = g.getFooterElement();
					el.style.display = "none";
					var el = g.getNavPaneElement();
					el.style.display = "none";
					
					
					if( !this.unsafeWindow.top._asyncFrames ) this.unsafeWindow.top._asyncFrames = {};
					this.unsafeWindow.top._asyncFrames[gtdFrame] = true;
				}	//else{	// initialise
				
					var elNav = this.gmailDOM.element("NavPaneElement", g);
					this._asyncPopuper = new AsyncPopuper(this, elNav.ownerDocument.body);
					this._contactFilterPopuper = new ContactFilterPopuper(this, elNav.ownerDocument.body);
					this._threadList = new ThreadList(this);
					GIPROTOTYPE.decodeEntities("0", this.doc);	// initialise it
					this.addCSS(this.gmailDOM.element("document", g));
					this.addCSS(this.doc);
					this._environment = new Environment(this, this.gmailDOM.element("MastheadElement", g));
					this._labels = new Labels(this);
					this._labels.load(elNav);
					this._threadListUI = new ThreadListUI(this);
					this._threadListPopupUI = new ThreadListPopupUI(this, elNav.parentNode);
					this._composeUI = new ComposeUI(this);
					this._conversationUI = new ConversationUI(this);
					
					this._lightbox = new Lightbox(this, this.doc.body);
					
					if( this.gtdinboxBrowser.showMsg ){
						this._lightbox.setType( this.gtdinboxBrowser.showMsg );
						this._lightbox.active(true);
						this.gtdinboxBrowser.showMsg = null;	// ensure doesn't show again on reload
					}
				//}
				
				this._createAboutBox();
				
			}catch(e){
				if( GTDDEBUGMODE ) alert("gmonkey call back main objects\n" + e.toString());
			}
		}
		this.viewChange(g);
		
	});
	this.unsafeWindow.GTDInterceptEval = GIPROTOTYPE.bind(this, function(a){
		if( !((typeof a == "object") && (typeof a.length == "number")) ) return;
		a = a[0];
		this.dataChange(a);
	});
	
	
	this.windowLoaded = false;
	window.addEventListener('load', GIPROTOTYPE.bind(this, function() {

		if( this.windowLoaded==false ){				
			this.unsafeWindow.gtdinboxFrame = gtdFrame? true:false;
			var elScript = this.doc.createElement("SCRIPT");
			elScript.src = "chrome://gtdinbox/content/GTDInboxLocal.js";
			this.doc.getElementsByTagName("HEAD")[0].appendChild(elScript);
			this.windowLoaded = true;
		}
		
	}), true);
	
};
GTDInboxPage.prototype.attachToBrowser = function(){
	this.browser = gBrowser.getBrowserForDocument( this.doc );
	this.browser.gtdinboxPage = this;
};
GTDInboxPage.prototype.addCSS = function(doc){
	var elLink = this.doc.createElement("LINK");
	elLink.type = "text/css";
	elLink.href = "chrome://gtdinbox/skin/gtdinbox.css";
	elLink.rel = "stylesheet";
	doc.getElementsByTagName("HEAD")[0].appendChild( elLink );
};

GTDInboxPage.prototype._createAboutBox = function(){
	this.elAbout = this._gmail.addNavModule("GTDInbox");
	
	var el = this.doc.createElement("DIV");
		el.className = "gtdinbox-about";
	this.elAbout.appendChild( el );
	
	var elOptions = this.doc.createElement("DIV");
		elOptions.className = "options";
	elOptions.innerHTML = "Options";	// TODO language
	el.appendChild(elOptions);
		
	//this.eventObservers.observe(elOptions, "mouseup", this._showOptions, false);
	elOptions.addEventListener("mousedown", GIPROTOTYPE.bind(this, function(){this._showOptions()}), true);
};
GTDInboxPage.prototype._showOptions = function(event){
try{
	this._lightbox.setType( "options" );
	this._lightbox.active(true);
}catch(e){
	if( GTDDEBUGMODE ) alert("gtdinboxpage _showOptions\n" + e.toString());
}
};

/*
GTDInboxPage.prototype.element = function(name, gmail){
	gmail = gmail || this._gmail;
	if( gmail["get" + name] ) return gmail["get" + name]();
	
	switch(name){
		case "document":
			return gmail.getActiveViewElement().ownerDocument;
			break;
		case "action-combo":
			var elActive = gmail.getActiveViewElement(); // //div[@class='sGcZQb']
			var result = this.doc.evaluate("//div[@gtdviewid='" + this.view("gtdviewid") + "']//div[@class='QOD9Ec']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "action-combo-list":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@class='Sn99bd']", elActive, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			for( var i = 0; i < result.snapshotLength; i++ ){
				if( result.snapshotItem(i).style.visibility!="hidden" ) return result.snapshotItem(i);
			}
			//return result.singleNodeValue;			
			break;
		case "alert-box":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@class='n38jzf']//table[@class='cyVRte']//td[@class='m14Grb']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "search-box":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@class='oF1kyb']//div[@class='tYBwhe']//input[@type='text']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "search-button":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@class='oF1kyb']//div[@class='tYBwhe']//button[@type='button']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "archive-button":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@gtdviewid='" + this.view("gtdviewid") + "']//button[@act='7']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "spam-button":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@gtdviewid='" + this.view("gtdviewid") + "']//button[@act='9']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "delete-button":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@gtdviewid='" + this.view("gtdviewid") + "']//button[@act='10']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "inbox-link":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@class='diLZtc']//div[@class='yyT6sf PQmvpb']//span[@class='zD5BAe']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "compose-mail":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@class='diLZtc']//div[@class='NIPhib']//span[@class='zD5BAe']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "threadlist-refresh":
			var elActive = gmail.getActiveViewElement();
			var result = this.doc.evaluate("//div[@gtdviewid='" + this.view("gtdviewid") + "']//div[@act='20']", elActive, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return result.singleNodeValue;
			break;
		case "contacts-frame-body":
			var w = this.window.frames[1];
			for( var i = 0; i < w.frames.length; i++ ){
				if( w.frames[i].location.href.indexOf("ui/ContactManager")>-1 ){
					return w.frames[i].document.body;
				}
			}
			break;
	}
};
*/

GTDInboxPage.prototype.view = function(name){
	name = name || "view";
	switch(name){
		case "gtdviewid":
			return this._viewid;
			break;
		case "view":
			return this._gmail.getActiveViewType();
			break;
	};
};

GTDInboxPage.prototype.viewChange = function(gmail){
	if( !gmail ){
		if( GTDDEBUGMODE ) alert("gtdinboxpage viewChange\nCould not find gmail");
		return;
	}
	this._gmail = gmail;
	var elActive = gmail.getActiveViewElement();
		
	this._viewid = (new Date()).valueOf();
	elActive.setAttribute("gtdviewid", this._viewid);
	
	this.eventObservers.reset();
	this._labels.viewChange(gmail);
	this.gmailDOM.viewChange(gmail);
	
	try{
		switch(gmail.getActiveViewType()){
			case "tl":	// threadlist
				this._threadListUI.viewChange( gmail );
				break;
			case "cv":	// conversation
				this._conversationUI.viewChange(gmail);
				break;
			case "co":	// compose
				this._composeUI.viewChange(gmail);
				break;
			case "ct":	// contacts
				this._contactFilterPopuper.viewChange(gmail);
				break;
			case "s":	// settings
				break;
		}
	}catch(e){
		if( GTDDEBUGMODE ) alert("viewChange\n" + e.toString());
	}
};

GTDInboxPage.prototype.dataChange = function(a){
	try{
		if( this._threadList ) this._threadList.parseAjaxResponse(a);
		if( this._environment ) this._environment.parseAjaxResponse(a);
		//this._labels.parseAjaxResponse(a);
		
		// Execute a Refresh when all data objects loaded for first time (only for Inbox; useful for auto label)
		if( !this._firstFullLoad && this._threadList._threads.length>0 && this._threadList._threads.length==this._threadListUI.rowCount ){
			this._firstFullLoad = true;
			this._threadListUI.refresh(null, true);
		}
	}catch(e){
		if( GTDDEBUGMODE ) alert("dataChange\n" + e.toString());
	}
};



GTDInboxPage.prototype.search = function(str){
		var elInput = this.gmailDOM.element("search-box");
	var elSubmit = this.gmailDOM.element("search-button");
	
	elInput.value = str;
	GIPROTOTYPE.doMouseEvent( this.doc, elSubmit, "click");
};


GTDInboxPage.prototype.unload = function(){
	// Clear up variables
	try{
	
	if( !this.doc && !this.browser ) return;
	
	if( this._threadList ) this._threadList.destroy();
	if( this._labels ) this._labels.destroy();
	if( this._threadListUI ) this._threadListUI.destroy();

	this.browser.gtdinboxPage = null;
	delete this.browser.gtdinboxPage;
			
	this.tab = null;
	this.browser = null;
	this.doc = null;

	}catch(e){if( GTDDEBUGMODE ) alert("gtdinboxPage unload\n" + e.toString())}
};

